import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutterdemo/0demo/bloc/multi_state_bloc/multi_state_bloc.dart';
import 'package:flutterdemo/0demo/bloc/multi_state_bloc/sub_widget.dart';

class MultiStateBlocTestPage extends StatefulWidget {
  const MultiStateBlocTestPage({Key key}) : super(key: key);

  @override
  _MultiStateBlocTestPageState createState() => _MultiStateBlocTestPageState();
}

class _MultiStateBlocTestPageState extends State<MultiStateBlocTestPage> {
  MultiStateBloc _bloc;

  @override
  void initState() {
    _bloc = MultiStateBloc(PageViewState(false, true))..add(DataChangeEvent("init"));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      // return BlocProvider.value(
      // value: _bloc,
      // 这里也可以用.value，但必须手动关闭bloc
      // 看注释可以发现，.value和create的却别还有实例问题
      create: (BuildContext context) => _bloc,
      child: BlocBuilder<MultiStateBloc, MultiState>(
        builder: (BuildContext context, state) {
          return Scaffold(
            appBar: AppBar(
              title: Text("multi state bloc"),
            ),
            body: _getContent(state),
          );
        },
      ),
    );
  }

  Widget _getContent(state) {
    if (state is PageViewState) {
      if (state.isLoading) {
        return Center(
          child: CircularProgressIndicator(),
        );
      }
      if (!state.isNetOk) {
        return Center(
          child: Text("no network"),
        );
      }
    }
    if (state is DataState) {
      return Stack(
        children: [
          Padding(
            padding: const EdgeInsets.all(20),
            child: Text(state.data ?? ""),
          ),
          Align(
            alignment: Alignment.center,
            child: SubWidget(bloc: _bloc),
          ),
          Align(
            alignment: Alignment.bottomRight,
            child: Padding(
              padding: const EdgeInsets.all(20),
              child: FloatingActionButton(
                onPressed: () {
                  _bloc.add(DataChangeEvent("data!"));
                },
                child: Text("get data"),
              ),
            ),
          )
        ],
      );
    }
    return Container();
  }

  @override
  void dispose() {
    _bloc?.close();
    super.dispose();
  }
}
